'''
concurrent.futures模块提供了高度封装的异步调用接口
ThreadPoolExecutor：线程池，提供异步调用
ProcessPoolExecutor: 进程池，提供异步调用
'''
from concurrent.futures import ProcessPoolExecutor,ThreadPoolExecutor
import os,time,random
def task(n):
    print('主进程%s is runing,子线程 %s' %(os.getpid(),os.getppid()))
    time.sleep(random.randint(1,3))
    return n**2

if __name__ == '__main__':

    executor = ThreadPoolExecutor(max_workers=3)
    # features = []
    # for i in  range(10):
    #     feature = executor.submit(task,i)#拿到的是一个future对象obj，需要用obj.result()拿到结果
    #     features.append(feature)
    # executor.shutdown(True)
    # print(">>>>>>>>>>>>>>")
    # for i in features:
    #     print(i.result())
    features = executor.map(task, range(1, 12))  # map取代了for+submit返回的是每一个线程返回的结果的一个生成器
    '''
    相当于进程池的pool.close()+pool.join()操作
    wait=True，等待池内所有任务执行完毕回收完资源后才继续
    wait=False，立即返回，并不会等待池内的任务执行完毕
    但不管wait参数为何值，整个程序都会等到所有任务执行完毕
    submit和map必须在shutdown之前
    '''
    executor.shutdown(True)
    print(">>>>>>>>>>>>>>")
    for i in features:
        print(i)



    # executor=ProcessPoolExecutor(max_workers=3)
    # futures=[]
    # for i in range(11):
    #     future=executor.submit(task,i)
    #     futures.append(future)
    # executor.shutdown(True)
    # print('+++>')
    # for future in futures:
    #     print(future.result())